package com.huawei.bitfun.insight;

import com.alibaba.fastjson.JSONObject;
import com.huawei.deveco.insight.ohos.common.ProfilerException;
import com.huawei.deveco.insight.ohos.common.Response;
import com.huawei.deveco.insight.ohos.resourcehandler.controller.HandlerMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;

public class InsightExRequestDispatcher {
    private static final Logger LOGGER = LoggerFactory.getLogger(InsightExRequestDispatcher.class);

    private static volatile InsightExRequestDispatcher instance = null;

    private InsightExRequestDispatcher() {

    }

    public static InsightExRequestDispatcher getInstance() {
        if (instance == null) {
            synchronized (InsightExRequestDispatcher.class) {
                if (instance == null) {
                    instance = new InsightExRequestDispatcher();
                }
            }
        }
        return instance;
    }
    public Response<?> dispatch(List<String> pathList, JSONObject params) throws ProfilerException {
        Optional<HandlerMethod> optionalHandlerMethod =
                InsightExMappingRegistryManager.getInstance().getHandlerMethod(pathList);
        if (optionalHandlerMethod.isEmpty()) {
            return Response.nonCallback();
        }
        Method method = optionalHandlerMethod.get().getMethod();
        method.setAccessible(true);
        try {
            Object result = method.invoke(null, params);
            if (result instanceof Response<?> response) {
                return response;
            } else {
                return Response.nonCallback();
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            if (e.getCause() instanceof ProfilerException) {
                throw (ProfilerException) e.getCause();
            }
            LOGGER.warn("Invoke method error", e);
            return Response.success("");
        }
    }
}
